<template>
    <div>
    </div>
</template>

<script>
  import Bus from '../util/bus';

  export default {
    name: 'websocketWorker',
    data() {
      return {
        user: null,
        websock: null
      }
    },
    methods: {
      initWebSocket() {
        //ws地址
        const wsUri = "ws://118.89.24.43:8080/yunmusic/commentNotification?userId=" + this.user.id;
        this.websock = new WebSocket(wsUri);
        this.websock.onmessage = this.websocketOnMessage;
        this.websock.onclose = this.websocketClose;
      },
      sendToServer(agentData){
        //若是ws开启状态
        if (this.websock.readyState === this.websock.OPEN) {
          this.websocketSend(agentData)
        }
        // 若是 正在开启状态，则等待300毫秒
        else if (this.websock.readyState === this.websock.CONNECTING) {
          let that = this;//保存当前对象this
          setTimeout(function () {
            that.websocketSend(agentData)
          }, 300);
        }
      },
      websocketOnMessage(res) {
        console.log(res)
        const data = JSON.parse(res.data);

        if (data.allow !== null && data.allow !== undefined) {
          if (data.allow === true) {
            this.$notify.info({
              title: '通知',
              message: "恭喜您成为音乐人！"
            });

            Bus.$emit("is-artist", data);

          } else {
            this.$notify.info({
              title: '通知',
              message: "您的音乐人申请被驳回！"
            });
          }

        }
        // 发送给top
        Bus.$emit("update-messageNum", data);
      },
      websocketSend(dataToSend) {
        this.websock.send(dataToSend);
      },
      websocketClose(res) {
        console.log(res)
        console.log("connection closed (" + res.code + ")")
        this.user = null;
        this.websock = null;
      }
    },
    mounted() {
      let _this = this;

      Bus.$on('on-websocket-open', function (user) {
        console.log("on")
        console.log(user)
        _this.user = user;
        _this.initWebSocket();
      });

      Bus.$on('on-websocket-send', function (data) {
        if (_this.user === null || _this.websock === null) {
          return;
        }
        _this.sendToServer(data)
      })

    }
  }
</script>

<style scoped>

</style>
